<template>
  <div class="container">
    <!-- 搜索 -->
    <div style="margin: 10px 0;">
      <el-form inline="true">
        <el-form-item label="查询类型">
          <el-select v-model="searchType" placeholder="请选择查询类型">
            <el-option label="ISBN" value="ISBN"></el-option>
            <el-option label="图书名称" value="name"></el-option>
            <el-option label="作者" value="author"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="查询目标">
          <el-input v-model="searchTarget" placeholder="请输入查询目标" clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 1%" @click="load" size="small">
            <svg-icon iconClass="search" />
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="danger" @click="clear">重置</el-button>
        </el-form-item>
        <!-- <el-form-item style="float: right" v-if="numOfOutDataBook != 0">
          <el-popconfirm confirm-button-text="查看" cancel-button-text="取消" :icon="InfoFilled" icon-color="red"
            title="您有图书已逾期，请尽快归还" @confirm="toLook">
            <template #reference>
              <el-button type="warning">逾期通知</el-button>
            </template>
          </el-popconfirm>
        </el-form-item> -->
      </el-form>
    </div>

    <!-- 当前借阅表格 --> 
    <el-divider content-position="left">当前借阅</el-divider>
    <el-table :data="tableData.rows" class="book-table" border>
      <el-table-column fixed prop="bookName" label="书名" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="borrowDate" label="借阅日期" />
      <el-table-column prop="deadLine" label="应还日期" />
      <el-table-column prop="isbn" label="ISBN" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleReturn(row)">归还</el-button>
        </template>
      </el-table-column>
      <!-- <el-pagination layout="prev, pager, next" :total="1000" /> -->
    </el-table>
    <!--    <div class="pagination">-->
    <!--      <el-pagination layout="prev, pager, next" :total="1000"/>-->
    <!--    </div>-->


    <!-- 历史借阅表格 -->
    <el-divider content-position="left" style="margin-top: 50px;">历史借阅</el-divider>
    <el-table :data="historyData.rows" class="book-table" border>
      <el-table-column fixed prop="bookName" label="书名" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="borrowDate" label="借阅日期" />
      <el-table-column prop="deadLine" label="应还日期" />
      <el-table-column prop="returnDate" label="归还日期" />
      <el-table-column prop="isbn" label="ISBN" />
      <!-- <el-pagination layout="prev, pager, next" :total="1000" /> -->
    </el-table>
    <!--    <div class="pagination">-->
    <!--      <el-pagination layout="prev, pager, next" :total="1000"/>-->
    <!--    </div>-->

  </div>
</template>
<script setup>
import request from '../utils/request'
import { onBeforeMount ,onMounted, onBeforeUpdate, ref, getCurrentInstance } from 'vue';
import { useMainStore } from "../store/index";
import { ElMessage } from 'element-plus'

const instance = getCurrentInstance()
const store = useMainStore()
const tableData = ref([])
const historyData = ref([])
const searchType = ref('')
const searchTarget = ref('')

onBeforeMount(() => {
  load()  
})

// onBeforeUpdate(() => {
//   returnFormatedTime()
// })

async function fetchData() {
  try {
    request.get('/records', {
      params: {
        userName: store.userName,
      }
    }).then((res) => {
      tableData.value = res.data
      console.log(tableData.value)
    })
  } catch (error) {
    console.log(error)
  }
}

async function fetchHistoryData() {
  try {
    request.get('/records/histories', {
      params: {
        userName: store.userName,
      }
    }).then((res) => {
      historyData.value = res.data
    })
  } catch (error) {
    console.log(error)
  } 
}

const load = () => {
  fetchData()
  fetchHistoryData()
}

const formatTime = (time) => {
  // const date = new Date(time);
  // const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' };
  // return date.toLocaleDateString('en-US', options);

  return time.replace('T', ' ') // 美化时间格式
}

// const returnFormatedTime = () => {
//   for (let i = 0; i < tableData.value.total; i++) {
//     tableData.value.rows[i].borrowDate = formatTime(tableData.value.rows[i].borrowDate)
//     console.log(tableData.value.rows[i].borrowDate)
//     tableData.value.rows[i].deadLine = formatTime(tableData.value.rows[i].deadLine)
//   }
//   for (let i = 0; i < tableData.value.total; i++) {
//     historyData.value.rows[i].borrowDate = formatTime(historyData.value.rows[i].borrowDate)
//     historyData.value.rows[i].deadLine = formatTime(historyData.value.rows[i].deadLine)
//     historyData.value.rows[i].returnDate = formatTime(historyData.value.rows[i].returnDate)
//   }
// }

const clear = () => {
  searchType.value = ''
  searchTarget.value = ''
}

const handleReturn = (book) => {
  request.put('/records', {
    userName: store.userName,
    isbn: book.isbn
  })
    .then(response => {
      if (response.code = 1) {
        ElMessage({
          message: '归还成功',
          type: 'success',
        })
        load()
      } else {
        ElMessage.error('归还失败')
      }
    })
    .catch(error => {
      ElMessage.error('网络请求错误')
      console.error(error);
    });
};


</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  position: relative;
  min-height: 30vh;
  overflow-x: hidden;
  margin-top: 10px;

  .book-table {
    align-self: center;
    width: 80%;
    margin-top: 20px;
    max-height: 32vh;
  }

  .pagination {
    position: absolute;
    bottom: 10px;
    left: 35%;
    justify-items: center;
  }

  .add-form {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000; // 浮动在其他内容之上
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(5px); // 对背景进行模糊处理
    z-index: 999; // 确保覆盖层位于内容之上但在表单之下
  }

}
</style>